<template>
  <div>
    <!--面包屑模块-->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="padding: 10px">
      <el-breadcrumb-item :to="{ path: '/student/' + this.studentID }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>班级申请</el-breadcrumb-item>
    </el-breadcrumb>
    
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>班级申请</span>
      </div>
      
      <!-- 可申请班级列表 -->
      <el-table :data="classList" border stripe>
        <el-table-column type="index" label="#" width="50"></el-table-column>
        <el-table-column prop="className" label="班级名称" width="180"></el-table-column>
        <el-table-column prop="teacherName" label="任课教师" width="120"></el-table-column>
        <el-table-column prop="description" label="班级描述"></el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="showApplyDialog(scope.row)">申请加入</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 15px">
      </el-pagination>
    </el-card>
    
    <!-- 我的申请记录 -->
    <el-card class="box-card" style="margin-top: 20px">
      <div slot="header" class="clearfix">
        <span>我的申请记录</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="getMyApplications">刷新</el-button>
      </div>
      
      <el-table :data="applicationList" border stripe>
        <el-table-column type="index" label="#" width="50"></el-table-column>
        <el-table-column prop="className" label="班级名称" width="180"></el-table-column>
        <el-table-column prop="applyTime" label="申请时间" width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.applyTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag type="info" v-if="scope.row.status === 'pending'">待审核</el-tag>
            <el-tag type="success" v-else-if="scope.row.status === 'approved'">已通过</el-tag>
            <el-tag type="danger" v-else-if="scope.row.status === 'rejected'">已拒绝</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reason" label="申请理由"></el-table-column>
        <el-table-column prop="remark" label="审核备注"></el-table-column>
        <el-table-column prop="handleTime" label="处理时间" width="180">
          <template slot-scope="scope">
            {{ scope.row.handleTime ? formatDate(scope.row.handleTime) : '-' }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 申请加入班级对话框 -->
    <el-dialog title="申请加入班级" :visible.sync="applyDialogVisible" width="40%">
      <el-form :model="applyForm" :rules="applyFormRules" ref="applyFormRef" label-width="100px">
        <el-form-item label="班级名称">
          <el-input v-model="applyForm.className" disabled></el-input>
        </el-form-item>
        <el-form-item label="申请理由" prop="reason">
          <el-input type="textarea" v-model="applyForm.reason" :rows="4" placeholder="请输入申请理由"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="applyDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitApply">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'ClassApply',
  data() {
    return {
      studentID: sessionStorage.getItem('userID'),
      // 查询参数
      queryInfo: {
        pageNum: 1,
        pageSize: 10
      },
      // 总数据条数
      total: 0,
      // 班级列表
      classList: [],
      // 申请列表
      applicationList: [],
      // 申请对话框
      applyDialogVisible: false,
      // 申请表单
      applyForm: {
        classId: '',
        className: '',
        studentId: '',
        reason: ''
      },
      // 表单验证规则
      applyFormRules: {
        reason: [
          { required: true, message: '请输入申请理由', trigger: 'blur' },
          { min: 5, max: 500, message: '长度在 5 到 500 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getClassList()
    this.getMyApplications()
  },
  methods: {
    // 获取班级列表
    async getClassList() {
      try {
        const { data: res } = await this.$http.get('/class/list', {
          params: {
            pageNum: this.queryInfo.pageNum,
            pageSize: this.queryInfo.pageSize
          }
        })
        
        if (res.code === 200) {
          this.classList = res.data.list || []
          this.total = res.data.total || 0
        } else {
          this.$message.error('获取班级列表失败')
        }
      } catch (error) {
        console.error('获取班级列表失败', error)
        this.$message.error('获取班级列表失败')
      }
    },
    
    // 获取我的申请记录
    async getMyApplications() {
      try {
        const { data: res } = await this.$http.get(`/class/application/student/${this.studentID}`)
        
        if (res.code === 200) {
          this.applicationList = res.data || []
        } else {
          this.$message.error('获取申请记录失败')
        }
      } catch (error) {
        console.error('获取申请记录失败', error)
        this.$message.error('获取申请记录失败')
      }
    },
    
    // 显示申请对话框
    showApplyDialog(row) {
      this.applyForm.classId = row.classId
      this.applyForm.className = row.className
      this.applyForm.studentId = this.studentID
      this.applyForm.reason = ''
      
      this.applyDialogVisible = true
    },
    
    // 提交申请
    submitApply() {
      this.$refs.applyFormRef.validate(async valid => {
        if (!valid) return
        
        try {
          const { data: res } = await this.$http.post('/class/application/apply', this.applyForm)
          
          if (res.code === 200) {
            this.$message.success('申请提交成功')
            this.applyDialogVisible = false
            this.getMyApplications()
          } else {
            this.$message.error(res.message || '申请提交失败')
          }
        } catch (error) {
          console.error('申请提交失败', error)
          this.$message.error('申请提交失败')
        }
      })
    },
    
    // 每页显示条数改变
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize
      this.getClassList()
    },
    
    // 当前页改变
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage
      this.getClassList()
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '-'
      const date = new Date(dateStr)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    }
  }
}
</script>

<style scoped>
.el-card {
  margin-bottom: 20px;
}
</style>
